﻿package ygg.exporter
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	import ygg.filetype.swf.Swf;
	import ygg.encoding.swf.SwfHeader;
	import ygg.encoding.swf.tag.*;
	import ygg.encoding.swf.tag.object.*;
	import ygg.encoding.swf.abc.*;
	import ygg.encoding.swf.abc.object.*;
	
	import j.sus2maj7.util.*;
	import j.sus2maj7.context.*;
	import j.sus2maj7.exporter.*;
	
	public class SwfExporter extends AbstractExporter
	{
		override public function export(o:*, context:IContext=null):void
		{
			trace(context.vars.rootDir.nativePath);
			
			var swf:Swf = Swf(o);
			writeStats(swf, context);
			trace(context.vars.rootDir.nativePath);
			
			var expFactory:TagExporterFactory = new TagExporterFactory()
			
			for each (var te:TagEncoding in swf.tags)
			{
				expFactory.getExporter(te.type).export(te.object, context);
			}
		}
		
		
		private function writeStats(swf:Swf, context:IContext=null):void
		{
			var h:SwfHeader = swf.header;
			
			var x:XML =
			<swf version={h.version} fileLength={h.fileLength} frameWidth={h.frameSize.width} frameHeight={h.frameSize.height} frameRate={h.frameRate} numFrames={h.frameCount}></swf>;
			
			var op:ObjectPrinter = new ObjectPrinter();
			op.MAX_LEVELS = 8;
			
			var node:XML;
			var node2:XML;
			for each (var te:TagEncoding in swf.tags)
			{
				node = <tag type={TagType.getName(te.type)} code={te.type} length={te.binary.length} />
				
				node2 = op.printToXml(te.object);
				
				node.appendChild(node2);
				x.appendChild(node);
				
			}
			
			var f:File = context.vars.rootDir.resolvePath('_info.xml');
			var fs:FileStream = new FileStream();
			fs.open(f, FileMode.WRITE);
			fs.writeUTFBytes(x.toXMLString() );
			fs.close();
		}
		
		
	}
}